require "json"
require "router"
require "http/params"
require "./amjil/*"

class WebServer
  include Router
  @@hashids = Hashids.new
  @@base = 10000000000

  def draw_routes

    post "/invate" do |context, params|
      body = context.request.body.not_nil!.gets_to_end

      if body
        params = JSON.parse body
        ret_code = 0
        message = ""

        if params["key"] && params["key"] != ""
          code, value = Store.get(params["key"].to_s)
          if code == 1 && value && value != ""
            Store.delete(params["key"].to_s)
            ret_code = 1
            message = "成功"
          else
            message = "邀请码不存在"
          end
        else
          ret_code, message = [0, "params error"]
        end

        ret_json = {code: ret_code, message: message}.to_json
        context.response.print ret_json
      else
        ret_json = {code: 0, message: "No params"}.to_json
        context.response.print ret_json
      end
      context
    end

    get "/:id" do |context, params|
      code, value = Store.get(params["id"])
      if code == 1 && value && value != ""
        ret_json = {code: 1, message: "邀请码可用"}.to_json
        context.response.print ret_json
      else
        ret_json = {code: 0, message: "邀请码不可用"}.to_json
        context.response.print ret_json
      end
      context
    end
  end

  def run
    server = HTTP::Server.new("0.0.0.0", 4002, [
      HTTP::LogHandler.new,
      HTTP::CompressHandler.new,
      route_handler])
    server.listen
  end
end

# Store.delete("cursor")
web_server = WebServer.new
web_server.draw_routes
web_server.run
